#!/usr/bin/env python3

""" Hydra Paste
    A libre paste engine with lots of power.

    Licensed under the GNU Affero Public License Version 3
        or Later. See LICENSES/LICENSE-AGPL for details.
    (c) Copyright 2015 Hydra Group
"""

import dataset
import os
from sys import path

# Ugly import hack
path.insert(1, 'lib/')
import safeurl

# For now, we're just deleting shit

# be sure to manually change this
# hardlinked for now
DIR_FILES = '/var/www/p/files'
DATABASE_FILE = '/var/www/p/db.sqlite'

def delete_files(listname):
    '''
    Delete files specified earlier
    '''
    db = dataset.connect('sqlite:///{}'.format(DATABASE_FILE))

    with open(listname, 'rt') as filelist:
        print(filelist)
        for f_name in filelist:
            f_name = f_name.rstrip()

            key_num = safeurl.num_decode(f_name)
            #print('have key num: {}'.format(key_num))
            result = db['files'].find_one(key=key_num)

            try:
                #print('flag 1')
                if result:
                    print('flag 2')
                    os.remove(os.path.join(DIR_FILES, f_name))
                    print('flag 3')
                    db['files'].delete(key=key_num)
                    print('Deleted {}'.format(f_name))
                elif not os.access(os.path.join(DIR_FILES, f_name), os.X_OK):
                    #print('file {} does not exist!'.format(f_name))
                    pass
                elif os.access(os.path.join(DIR_FILES, f_name), os.X_OK):
                    print('file {} exists!'.format(f_name))
                else:
                    print('Couldn\'t find {}'.format(f_name))
            except Exception as e:
                # File must not exist anymore. Carry on. Meh
                print('error: {}'.format(e))

def main():
    print('hai')
    delete_files('delete.txt')

if __name__ == '__main__':
    main()
